#![allow(unused_assignments)]
extern crate querystring;

use axum::{
    body::HttpBody,
    extract::{Request,Query},
    middleware::Next,
    response::{IntoResponse, Response},
};
use tower_sessions::Session;
use std::collections::HashMap;

use crate::serviceimpl::login_service::can_access;

pub async fn check_auth(Query(params):Query<HashMap<String, String>>,session: Session, req: Request, next: Next) -> Response
{
    let uri = req.uri().clone().to_string();
    let mut _token:String = "".to_string();
    if let Some(value) = params.get("token") {
        _token = value.clone();
    } else {
        if let Some(session_value) = session.get("token") .await.unwrap(){
            _token = session_value;
        }else {
            let headers = req.headers();
            _token = headers.get("X-Token").unwrap().to_str().unwrap().to_string();
        }
    }
   	if _token.is_empty() {
        return r#"{  "rows": null,  "success": false , "noAuth":true }"#.into_response();
   	}
	let can_access_bool  = can_access(_token,uri.clone()).await;

	if can_access_bool {
		let response = next.run(req).await;
		return response;
	}
	r#"{  "rows": null,  "success": false, "noAuth":true }"#.into_response()
}
